import { onMounted, reactive, ref, computed } from "vue";
import {
  getFeedbackListByCourseId,
  getAllVideoByCourseId,
  getCourseDetailById,
  addFeedback,
  addVideoReq,
  getUserHaveCourse,
  addUserCourse,
  cancelUserCourse
} from "@/api/course/index";
import { deleteVideo, updateVideo } from "@/api/video/index";
import {
  addStreaming,
  getLiveStreamingListByCourseId,
  // getLiveStreamingByStatus
  getLiveStreamingRoomUser,
  cancelLiveStreaming,
  updateLiveStreaming
} from "@/api/liveStreaming";
import { useRoute, useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage } from "element-plus";
import type { FormRules, UploadProps } from "element-plus";
import { imageUpload } from "@/api/common/index";
// import { QNURL } from "@/config/urlConfig";

export function useCourseHooks() {
  const route = useRoute();
  const router = useRouter();

  const userStore = useUserStoreHook();

  const courseId = route.query?.id || "";

  const feedbackList = ref<any>([]);

  const isTeacher = computed(() => userStore.getRoles?.includes("teacher"));

  const userInfo = computed(() => userStore.getUserInfo);

  const token = computed(() => userStore.getToken);

  const isSelcted = ref(true);

  async function getUserHaveCourseFun() {
    const res = await getUserHaveCourse({
      courseId: courseId,
      userId: userInfo.value?.userId || ""
    });

    if (res.code == 200) {
      isSelcted.value = true;
    } else {
      isSelcted.value = false;
    }
  }

  async function getFeedbackListFun() {
    const res = await getFeedbackListByCourseId({ id: courseId });

    feedbackList.value = res.data;
  }

  const videoList = ref<any>([]);

  async function getVideoListFun() {
    const res = await getAllVideoByCourseId({ id: courseId });

    videoList.value = res.data;
  }

  let courseDetail = reactive<any>({});

  async function getCourseDetailFun() {
    const res = await getCourseDetailById({ id: courseId });

    courseDetail = Object.assign(courseDetail, res.data);

    console.log(courseDetail);
  }

  // --------------------------------------------------- 课程反馈 --------------
  const courseFeedbackVisible = ref(false);
  const feedbackVal = reactive({
    feedback: ""
  });
  async function giveFeedback() {
    if (!isSelcted.value) {
      return ElMessage.error("请先学习该课程后再进行反馈！");
    }
    if (!token.value) {
      return ElMessage.error("请先登录");
    }
    courseFeedbackVisible.value = true;
  }

  async function comfirmHandel() {
    if (feedbackVal.feedback == "") {
      ElMessage.error("请输入内容");
      return;
    }
    const res = await addFeedback({
      content: feedbackVal.feedback,
      courseId: courseId,
      userId: userStore.getUserInfo?.userId
    });

    if (res.code == 200) {
      ElMessage.success("发表成功");
      courseFeedbackVisible.value = false;
      feedbackVal.feedback = "";
      getFeedbackListFun();
    }
  }

  // -------------------------------------
  const isAddVideo = ref(true);
  interface RuleForm {
    name: string;
    videoUrl: string;
    courseId: string;
    duration: number;
    id: string;
  }

  const rules = reactive<FormRules<RuleForm>>({
    name: [{ required: true, message: "请输入视频名称", trigger: "blur" }]
    // videoUrl: [{ required: true, message: "请先点击上传", trigger: "blur" }]
  });
  const addVideoVisible = ref(false);
  const videoInfoRuleFormRef = ref();
  const videoTotalTime = ref(0);
  const videoInfo = reactive<RuleForm>({
    name: "",
    videoUrl: "",
    courseId: courseId as string,
    duration: 0,
    id: ""
  });
  function addVideo(val = true, item?: any) {
    addVideoVisible.value = true;
    isAddVideo.value = val;

    if (val) return;
    videoInfo.duration = item.duration;
    videoInfo.name = item.name;
    videoInfo.videoUrl = item.videoUrl;
    videoInfo.courseId = item.courseId;
    videoInfo.id = item.id;
  }

  function videoClick(item: any, index: number) {
    if (!isSelcted.value && !isTeacher.value) {
      return ElMessage.error("请先将课程添加到我的课程学习中！");
    }
    router.push({
      path: "/video",
      query: {
        videoId: item?.id,
        courseId: item?.courseId,
        index: index
      }
    });
  }

  async function addVieoComfirmHandel() {
    if (!videoInfo.videoUrl) {
      ElMessage.error("请先点击上传按钮");
      return;
    }
    videoInfoRuleFormRef?.value.validate(async (vaild: boolean) => {
      if (vaild) {
        if (isAddVideo.value) {
          videoInfo.duration = videoTotalTime.value;

          const res = await addVideoReq(videoInfo);

          if (res.code == 200) {
            ElMessage.success("上传成功");
            addVideoVisible.value = false;
            videoInfo.name = "";
            videoInfo.videoUrl = "";
            getVideoListFun();
          }
          console.log(res);
        } else {
          const res = await updateVideo(videoInfo);

          if (res.code == 200) {
            ElMessage.success("修改成功");
            addVideoVisible.value = false;
            videoInfo.name = "";
            videoInfo.videoUrl = "";
            getVideoListFun();
          }
        }
      }
    });
  }

  function successUpload(val: string) {
    videoInfo.videoUrl = val;
  }

  function videoTime(val: number) {
    videoTotalTime.value = val;
  }

  async function deleteVideoFun(item: any) {
    const res = await deleteVideo({ id: item.id });

    if (res.code == 200) {
      ElMessage.success("删除成功");
      getVideoListFun();
    }
  }

  // -------------------- 直播 ---------------------
  interface LiveStreamingRuleForm {
    roomName: string;
    cover: string;
    roomIntroduce: string;
    orderTime: any;
    id: string;
    status: number;
  }

  const liveStreamingVisible = ref(false);

  const startLiveVisible = ref(false);

  const liveStreamingRuleFormRef = ref();

  const liveStreamingList = ref<any>([]);

  let liveStreamingRoomInfo = reactive<any>({});

  const isAddLiveStreaming = ref(true);

  const currentClickLiveStreamingRoomId = ref<any>("");

  const liveStreamingInfo = reactive<LiveStreamingRuleForm>({
    cover: "",
    roomName: "",
    roomIntroduce: "",
    orderTime: null,
    id: "",
    status: 0
  });

  const liveStreamingRules = reactive<FormRules<LiveStreamingRuleForm>>({
    roomName: [
      { required: true, message: "请输入直播间名称", trigger: "blur" }
    ],
    cover: [{ required: true, message: "请上传直播间封面", trigger: "blur" }],
    roomIntroduce: [
      { required: true, message: "请上传直播介绍", trigger: "blur" }
    ],
    orderTime: [{ required: true, message: "请选择直播时间", trigger: "blur" }]
  });

  function addLiveStreaming(val = true, item?: any) {
    liveStreamingVisible.value = true;
    isAddLiveStreaming.value = val;

    if (val) return;
    liveStreamingInfo.cover = item.cover;
    liveStreamingInfo.roomName = item.roomName;
    liveStreamingInfo.roomIntroduce = item.roomIntroduce;
    liveStreamingInfo.orderTime = item.orderTime;
    liveStreamingInfo.id = item.id;
    liveStreamingInfo.status = item.status;
  }

  const beforeAvatarUpload: UploadProps["beforeUpload"] = file => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isJpgOrPng) {
      ElMessage.error("只能上传 JPG/PNG 图片格式的文件");
      return false;
    }
    if (!isLt2M) {
      ElMessage.error("文件大小超过 2MB 的限制");
      return false;
    }

    // 使用自定义的方式上传文件
    const formData = new FormData();
    formData.append("image", file);

    uploadFile(formData);

    return false;
  };

  const uploadFile = async (formData: FormData) => {
    console.log(formData);
    try {
      const res = await imageUpload(formData);
      if (res.code === 200) {
        liveStreamingInfo.cover = res?.msg;
      }
    } catch (error) {
      console.error(error);
    }
  };

  async function liveStreamingComfirmHandel() {
    liveStreamingRuleFormRef.value &&
      liveStreamingRuleFormRef.value.validate(async (valid: any) => {
        if (valid) {
          if (isAddLiveStreaming.value) {
            const res = await addStreaming({
              userId: userStore.getUserInfo?.userId,
              courseId: courseId,
              cover: liveStreamingInfo.cover,
              roomName: liveStreamingInfo.roomName,
              roomIntroduce: liveStreamingInfo.roomIntroduce,
              orderTime: liveStreamingInfo.orderTime
            });

            if (res.code !== 200) return;

            ElMessage.success("添加成功");

            getLiveStreamingListFun();
          } else {
            const res = await updateLiveStreaming({
              id: liveStreamingInfo.id,
              userId: userStore.getUserInfo?.userId,
              courseId: courseId,
              cover: liveStreamingInfo.cover,
              roomName: liveStreamingInfo.roomName,
              roomIntroduce: liveStreamingInfo.roomIntroduce,
              orderTime: liveStreamingInfo.orderTime
            });

            if (res.code !== 200) return;

            ElMessage.success("修改成功");
            getLiveStreamingListFun();
          }

          liveStreamingInfo.cover = "";
          liveStreamingInfo.roomName = "";
          liveStreamingInfo.roomIntroduce = "";
          liveStreamingInfo.orderTime = "";
          liveStreamingVisible.value = false;
        } else {
          ElMessage.error("请填写完整信息");
        }
      });
  }

  async function getLiveStreamingListFun() {
    const res = await getLiveStreamingListByCourseId({
      id: courseId
    });

    liveStreamingList.value = res.data;
  }

  async function getLiveStreamingInfoFun() {
    const res = await getLiveStreamingRoomUser({
      id: currentClickLiveStreamingRoomId.value
    });

    liveStreamingRoomInfo = Object.assign(liveStreamingRoomInfo, res.data);
  }

  function liveStreamingClick(item: any, index: number) {
    if (item.status == 1) {
      router.push({
        path: "/live_streaming",
        query: {
          id: item.id,
          type: 0
        }
      });
      return;
    }

    if (item.status == 2) {
      router.push({
        path: "/live_streaming",
        query: {
          id: item.id,
          type: 1
        }
      });
      return;
    }
    console.log(item, index);
  }

  function liveStreamingStartClick(item: any, index: number) {
    console.log(item, index);
    currentClickLiveStreamingRoomId.value = item.id;
    const count = liveStreamingList.value.filter((t: any) => t.status == 1);

    if (count.length > 1) {
      ElMessage.error("只能同时开启一个直播");
      return;
    }

    startLiveVisible.value = true;
    getLiveStreamingInfoFun();
  }

  async function deleteLiveStreaming(item: any) {
    const res = await cancelLiveStreaming({ id: item.id });

    if (res.code == 200) {
      ElMessage.success("删除直播成功");
      getLiveStreamingListFun();
    }
  }

  function helpHandel() {
    window.open(
      "https://t1yk3sg1czy.feishu.cn/docx/RtLpdrqpJoKa2Px8onlcGPTjnL2?from=from_copylink",
      "_blank"
    );
  }

  function nextStep() {
    getLiveStreamingInfoFun();

    if (liveStreamingRoomInfo.status == 1) {
      ElMessage.success("直播已开启");
      router.push({
        path: "/live_streaming",
        query: {
          id: currentClickLiveStreamingRoomId.value
        }
      });
    } else {
      ElMessage.error("请先在obs推流软件中打开直播！");
    }
  }

  // ---------------------------------------------------------------

  async function addCourse() {
    const res = await addUserCourse({
      courseId: courseId,
      userId: userInfo.value?.userId || ""
    });

    if (res.code == 200) {
      ElMessage.success("已加入课程！");
      getUserHaveCourseFun();
    }
  }

  async function cancelUserCourseFun() {
    const res = await cancelUserCourse({
      courseId: courseId,
      userId: userInfo.value?.userId || ""
    });

    if (res.code == 200) {
      ElMessage.success("已取消课程！");
      getUserHaveCourseFun();
    }
  }

  onMounted(() => {
    getUserHaveCourseFun();
    getFeedbackListFun();
    getVideoListFun();
    getCourseDetailFun();
    getLiveStreamingListFun();
  });

  return {
    isSelcted,
    courseFeedbackVisible,
    feedbackVal,
    courseDetail,
    feedbackList,
    videoList,
    addVideoVisible,
    videoInfoRuleFormRef,
    videoInfo,
    rules,
    courseId,
    userInfo,
    liveStreamingList,
    liveStreamingVisible,
    liveStreamingInfo,
    liveStreamingRules,
    liveStreamingRuleFormRef,
    liveStreamingRoomInfo,
    startLiveVisible,
    isTeacher,
    isAddVideo,
    isAddLiveStreaming,
    deleteLiveStreaming,
    videoTime,
    videoClick,
    cancelUserCourseFun,
    liveStreamingStartClick,
    liveStreamingClick,
    addLiveStreaming,
    beforeAvatarUpload,
    liveStreamingComfirmHandel,
    giveFeedback,
    comfirmHandel,
    addVideo,
    addVieoComfirmHandel,
    successUpload,
    helpHandel,
    nextStep,
    addCourse,
    deleteVideoFun
  };
}
